#!/bin/csh
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#   TROPICAL STORM DETECTION 
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#===============================================================
# --- CHECK ARGUMENTS
#===============================================================

set nargin = $#argv
set xdir = ""

if ($nargin < 2) then
    echo
    echo "USAGE: " $0 " <inputfile> <outputdir>"
    echo
    echo "ARGUMENTS:"
    echo "\t<inputfile>: full path to input netCDF file"
    echo
    echo "\t<outputdir>: full path to output directory for multiple files; will be created if it does not exist"
    echo
    echo "\t<executabledir>: full path to directory with tstorms and trajectory executables"
    echo "\t\t\t(optional: necessary only if not already in PATH)"
    echo
    exit -1
else
    set fin = $1
    set dir_out = $2
    if ($nargin > 2) then
	set xdir = $3
    endif
endif

echo "inputfile = " $fin
echo "outputdir = " $dir_out

# n: only count potential tropical storms at isolated time steps
# y: after finding potential storms, link them into trajectories
set do_traj = n

# year, used as suffix for output files
#set year    = $1 

if ( ! -e $dir_out  ) mkdir -p $dir_out

#===============================================================
# --- SET SOME PATHNAMES
#===============================================================

# --- executables
if ($xdir == "") then
    set tstorms = tstorms_drive.exe
    set trajectory = trajectory.exe
else
    echo "executabledir = " $xdir
    set tstorms    = ${xdir}/tstorms_drive.exe
    set trajectory = ${xdir}/trajectory.exe
endif

# --- output data
set fcyc  = ${dir_out}/cyclones_out    # storm days
set ftraj = ${dir_out}/traj_out        # trajectories
set fori  = ${dir_out}/ori_out         # initial positions
set fstat = ${dir_out}/traj_stat_out   # total counts

#===============================================================
# --- TROPICAL STORM DETECTION 
#===============================================================

# --- data extraction
echo ${fin}
# ncks options:
#	-v: extract variables
#	-h: suppresses history concatenatino
#	-A: overwrites output file without prompt
#	-c:

#> echo 'Convert time units for easy parsing'
#> ncap2 -s 'time@units="days since 1979-10-01 00:00:00"' ${fin} ${dir_out}/temp1.nc
#> ncap2 -s "Z1000=float(287.0*TS*ln(PSL/100000.0)/9.81)" ${dir_out}/temp1.nc ${dir_out}/temp1.5.nc
#> echo 'Remove annoying average values'
#> ncwa -O -a nbnd,chars,ilev,lev ${dir_out}/temp1.5.nc ${dir_out}/temp2.nc
#> echo 'Subselect time'
#> #ncks -F -d time,1,,2 ${dir_out}/temp2.nc ${dir_out}/temp3.nc
#> #APE CHANGE
#> cp ${dir_out}/temp2.nc ${dir_out}/temp3.nc
#> rm ${dir_out}/temp1.nc ${dir_out}/temp1.5.nc ${dir_out}/temp2.nc
#> echo 'Remove global attributes (Bluefire oddly segfaults past 12 atts)'
#> ncatted -O -a ,global,d,, ${dir_out}/temp3.nc ${dir_out}/temp1.nc
#> ncks -v PSL,T200,T500,U850,UBOT,V850,VBOT,Z1000,ZBOT,Z200,VR850SM ${dir_out}/temp1.nc ${dir_out}/test1.nc
#> # APE CHANGE
#> #ncks -v PS,T200,T500,U850,UBOT,V850,VBOT,Z1000,Z200 ${dir_out}/temp1.nc ${dir_out}/test1.nc
#> rm ${dir_out}/temp1.nc
#> rm ${dir_out}/temp3.nc

ncks -v PSL,T200,T500,U850,UBOT,V850,VBOT,Z1000,ZBOT,Z200,VR850SM ${fin} ${dir_out}/test1.nc

ncks -h -A -c ${dir_out}/test1.nc ${dir_out}/test2.nc
ncks -h -A    ${dir_out}/test1.nc ${dir_out}/test2.nc


# --- set namelist

# if ( ! -e $dir_out/nml_input  ) then
# cat << eof > ${dir_out}/nml_input
#  &nml_tstorms
#    crit_vort =  1.0E-5,
#    crit_dist =  4.0,  
#     crit_twc =  0.8,   
#     dist_twc =  5.0, 
#   crit_thick =  50.0,  
#     crit_psl = 400.0,
#     dist_psl =   5.0,
#    lat_bound_n =  45.0,
#    lat_bound_s = -45.0,
#  /end
#  &nml_indata
#           fname = '${dir_out}/test2.nc',
#     use_sfc_wnd = .true.,
#    do_smoothing = .false.,
#            atwc = 0.333,
#  /end
# eof
# endif

if ( ! -e $dir_out/nml_input  ) then
cat << eof > ${dir_out}/nml_input
 &nml_tstorms
   crit_vort =  1.0E-4,
   crit_dist =  2.0,  
    crit_twc =  0.8,   
    dist_twc =  5.0, 
  crit_thick =  50.0,
  dist_thick =  5.0,
    crit_psl = 400.0,
    dist_psl =   5.0,
   lat_bound_n =  45.0,
   lat_bound_s = -45.0,
 /end
 &nml_indata
          fname = '${dir_out}/test2.nc',
    use_sfc_wnd = .true.,
   do_smoothing = .false.,
           atwc = 0.333,
 /end
eof
endif

# --- run program
$tstorms < ${dir_out}/nml_input

# --- save output
if !( -e $fcyc ) then
    touch $fcyc
endif

# need to change this in the source code and recompile
#if ( -e ${dir_out}/cyclones ) then
#    cat ${dir_out}/cyclones >> $fcyc

# for now, just use current working directory
if ( -e cyclones ) then
    cat cyclones >> $fcyc
    echo "  OUTPUT ADDED TO: " $fcyc
else
    echo "   "
    echo "  BUMMER: JOB FAILED"
    echo "   "
    goto tixe
endif

rm -f ${dir_out}/test1.nc ${dir_out}/test2.nc
#rm -f tstorms.exe

#===============================================================
# --- TRAJECTORY ANALYSIS
#===============================================================
if ( $do_traj == y ) then

# --- get executable
#cp $trajectory  trajectory.exe

#rm -f    cyclones
#cp $fcyc ${dir_out}/cyclones

cp $fcyc cyclones

if ( ! -e $dir_out/nml_trajectory  ) then
cat << eof > ${dir_out}/nml_trajectory
 &nml_trajectory
      wcrit =  17.5,
      rcrit =  400.0,
     nwcrit =  8,
    do_filt = .true.,
 /end
eof
endif

$trajectory < ${dir_out}/nml_trajectory

head -16  stats

# move to output directory
mv   ori  $fori
mv  traj  $ftraj
mv stats  $fstat

# delete copy of cyclones file
rm -f cyclones

endif




